//
//  LogPlugin.swift
//  CooperSwift
//
//  Created by Mac on 2019/12/25.
//  Copyright © 2019 CooperSwift. All rights reserved.
//

import Foundation
import Moya

public final class LogPlugin: PluginType {
    
    public init() {}
    
    /// Called to modify a request before sending.
    public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        return request
    }
    
    /// Called immediately before a request is sent over the network (or stubbed).
    public func willSend(_ request: RequestType, target: TargetType) {
        
    }
    
    /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        
    }
    
    /// Called to modify a result before completion.
    public func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> {
        let url = target.baseURL.absoluteString + target.path
        if case let .failure(error) = result {
            log.error("请求-->" + url)
            log.error("参数-->" + "\(target.task)")
            log.error("报错-->" + (error.errorDescription ?? ""))
        }
        if case let .success(response) = result {
            log.debug("请求-->" + url)
            log.debug("参数-->" + "\(target.task)")
            if let data = try? response.mapString() {
                log.debug("结果-->" + "\(data)")
            }
        }
        return result
    }
    
}
